package com.sky.utils;

import com.sky.constant.JwtClaimsConstant;
import com.sky.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Component
public class ParseJWTGetId {
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 从token中获取员工ID
     */
    public Integer getEmpId(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("Token");
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Integer empId = Integer.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
        return empId;
    }

    /**
     * 从token中获取用户ID
     */
    public Integer getUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || token.trim().isEmpty()) {
            log.warn("请求头中未找到Authorization token");
            // 尝试其他可能的token头字段
            token = request.getHeader("token");
            if (token == null) {
                token = request.getHeader("authentication");
            }
        }

        if (token == null || token.trim().isEmpty()) {
            log.error("请求头中未找到任何token信息");
            throw new RuntimeException("用户未登录");
        }

        // 清理token（可能包含Bearer前缀）
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);

            if (userIdObj instanceof Integer) {
                return (Integer) userIdObj;
            } else if (userIdObj instanceof Long) {
                return ((Long) userIdObj).intValue();
            } else if (userIdObj instanceof String) {
                return Integer.parseInt((String) userIdObj);
            } else {
                log.error("用户ID格式不正确: {}", userIdObj);
                throw new RuntimeException("用户ID格式不正确");
            }
        } catch (Exception e) {
            log.error("解析token失败: {}", e.getMessage());
            throw new RuntimeException("token无效", e);
        }
    }
}
